<!-- 登录组件创建 -->
<template>
  <section class="loginContainer">
    <div class="loginInner">
      <div class="login_header">
        <h2 class="login_logo">硅谷外卖</h2>
        <div class="login_header_title">
          <!-- 这里进行切换的方式是 class='on' 这样进行切换, 目前只有两种方式, 可以使用一个变量进行控制 -->
          <a href="javascript:;" :class="{on: codeLogin}" @click="changeLoginMethod(true)">短信登录</a>
          <a href="javascript:;" :class="{on: !codeLogin}" @click="changeLoginMethod(false)">密码登录</a>
        </div>
      </div>
      <div class="login_content">
        <form>
          <div :class="{on: codeLogin}">
            <section class="login_message">
              <input v-model="phone" type="tel" maxlength="11" placeholder="手机号">
              <button :disabled="!isRightPhone" :class="{right_phone: isRightPhone}" class="get_verification" @click.prevent="sendCode">
                {{codeText}}
              </button>
            </section>
            <section class="login_verification">
              <input v-model="code" type="tel" maxlength="8" placeholder="验证码">
            </section>
            <section class="login_hint">
              温馨提示：未注册硅谷外卖帐号的手机号，登录时将自动注册，且代表已同意
              <a href="javascript:;">《用户服务协议》</a>
            </section>
          </div>
          <div :class="{on: !codeLogin}">
            <section>
              <section class="login_message">
                <input v-model="name" type="tel" maxlength="11" placeholder="手机/邮箱/用户名">
              </section>
              <section class="login_verification">
                <input v-model="pwd" v-show="showPwd" type="text" maxlength="8" placeholder="密码">
                <input v-model="pwd" v-show="!showPwd" type="password" maxlength="8" placeholder="密码">
                <div class="switch_button" :class="showPwd ? 'on' : 'off'" @click="showPwd = !showPwd">
                  <div class="switch_circle" :class="{right: showPwd}">></div>
                  <span class="switch_text">{{showPwd ? 'abc' : '...'}}</span>
                </div>
              </section>
              <section class="login_message">
                <input v-model="captcha" type="text" maxlength="11" placeholder="验证码">
                <img class="get_verification" src="http://localhost:4000/captcha" alt="captcha" @click="getCaptcha" ref="captcha">
              </section>
            </section>
          </div>
          <button class="login_submit" @click.prevent="login">登录</button>
        </form>
        <a href="javascript:;" class="about_us">关于我们</a>
      </div>
      <a href="javascript:" class="go_back" @click="$router.go(-1)">
        <i class="iconfont icon-jiantou2"></i>
      </a>
    </div>
    <AlertTip v-show="showAlert" :alertText="alertText" @closeTip="closeTip"></AlertTip>
  </section>
</template>

<script>
// 导入警告框组件 
import AlertTip from '@/components/AlertTip/AlertTip'
import {
  reqSendcode,
  reqLoginSms,
  reqLogin
} from '../../api/index'

export default {
    data() {
        return {
            codeLogin: true,
            // 短信验证码登录 
            phone: '',
            code: '',
            // 账号密码登录
            name: '',
            pwd: '',
            captcha: '',
            showPwd: false,
          
            // 警告框控制函数
            showAlert: false,
            alertText: '',

            // 倒计时函数
            countDown: 0,
            intervalId: undefined
        }
    },

    components: {
      AlertTip
    },

    computed: {
      // 这里可以使用计算属性, 来判断手机号是否正确
      isRightPhone() {
        let res = /^1\d{10}$/.test(this.phone)
        console.log(res);
        return res
      },
      // 验证码处显示的图片 
      codeText() {
        let text = this.countDown > 0 ? '已发送' + this.countDown + 's' : '获取验证码'
        return text
      },
    },

    mounted() {},

    methods: {
      /* ================== 账号密码登录 ================== */ 
      getCaptcha(event) {
        event.target.src = 'http://localhost:4000/captcha?time='+Date.now()
      },
      async usernamePwdLogin() {
        if(!this.name) {
          this.showAlertFrame("请输入手机号/邮箱/用户名")
          return
        }
        if(!this.pwd) {
          this.showAlertFrame("密码不能为空")
          return
        }
        if(!this.captcha) {
          this.showAlertFrame("验证码不能为空")
          return
        }
        const {name , pwd , captcha} = this
        // 调用接口进行登录
        let result = await reqLogin({name , pwd , captcha})
        if (result.code === 0) {
            // 登录成功, 将当前的用户信息保存到 state 中 
            // this.showAlertFrame(result.data.phone)
            this.$store.dispatch('saveUserInfo' , result.data)
            // 跳转到其他页面 
             this.$router.replace('/profile')
          } else {
            // 登录失败, 提示
            this.showAlertFrame(result.msg)
            // 更换验证码
            this.$refs.captcha.src = 'http://localhost:4000/captcha?time='+Date.now()
          }
      },
      /* ================== 账号密码登录 ================== */ 

      login() {
        // 短信验证码登录
        if (this.codeLogin) {
          this.phoneCodeLogin()
        } else {
          this.usernamePwdLogin()
        }
      },
      async phoneCodeLogin() {
        // 表单校验 
          if (!this.phone || !this.code) {
            this.showAlertFrame("请输入手机号或者验证码")
          }
          // 发送请求 获取用户信息
          let result = await reqLoginSms(this.phone , this.code) 
          console.log(result);
          if (result.code === 0) {
            // 登录成功, 将当前的用户信息保存到 state 中 
            // this.showAlertFrame(result.data.phone)
            this.$store.dispatch('saveUserInfo' , result.data)
            // 跳转到其他页面 
             this.$router.replace('/profile')
          } else {
            // 登录失败, 提示
            this.showAlertFrame(result.msg)
          }
      },
      // 当前的登录方式
      changeLoginMethod(isCodeLogin) {
        this.codeLogin = isCodeLogin
      },
      // 发送验证码 
      async sendCode() {
        // 1 将当前的手机号, 进行验证, 是否为符合标准的手机号
        if (!this.isRightPhone) {
          // 这里进行手机号错误提示
          this.showAlertFrame("手机号验证失败, 请检查后重新发送验证码")
          return
        }
        //  1.1 补充: 这里需要判断是否已经启动倒计时, 如果已经启动了, 不管, 让他点
        if (this.intervalId) {
          return
        }
        //  1.2 补充: 这里需要进行倒计时
        this.countDown = 30
        this.intervalId =  setInterval(() => {
          if (this.countDown <= 0) {
            // 停止定时器 
            clearInterval(this.intervalId)
            this.intervalId = undefined
          } else {
            this.countDown = --this.countDown
          }
        } , 1000)
        // 2 使用当前的手机号, 进行发送验证码 , 调用后台接口
        // 3 验证码是否发送成功, 如果成功, 给个提示, 如果失败, 也给个提示
        let result = await reqSendcode(this.phone) 
        console.log(result);
        if (result.code === 1) {
          // 提示框, 验证码发送成功
          this.showAlertFrame("验证码发送失败, 请重新发送")
          clearInterval(this.intervalId)
          this.intervalId = undefined
          this.countDown = 0
        }
      },
      // 显示警告框
      showAlertFrame(alertText) {
        this.showAlert = true
        this.alertText = alertText
      },
      // 警告框回调函数
      closeTip() {
        this.showAlert = false
        this.alertText = ''
      }
    },
}
</script>
<style lang="stylus" rel="stylesheet/stylus">
.loginContainer {
  width: 100%;
  height: 100%;
  background: #fff;

  .loginInner {
    padding-top: 60px;
    width: 80%;
    margin: 0 auto;

    .login_header {
      .login_logo {
        font-size: 40px;
        font-weight: bold;
        color: #02a774;
        text-align: center;
      }

      .login_header_title {
        padding-top: 40px;
        text-align: center;

        >a {
          color: #333;
          font-size: 14px;
          padding-bottom: 4px;

          &:first-child {
            margin-right: 40px;
          }

          &.on {
            color: #02a774;
            font-weight: 700;
            border-bottom: 2px solid #02a774;
          }
        }
      }
    }

    .login_content {
      >form {
        >div {
          display: none;

          &.on {
            display: block;
          }

          input {
            width: 100%;
            height: 100%;
            padding-left: 10px;
            box-sizing: border-box;
            border: 1px solid #ddd;
            border-radius: 4px;
            outline: 0;
            font: 400 14px Arial;

            &:focus {
              border: 1px solid #02a774;
            }
          }

          .login_message {
            position: relative;
            margin-top: 16px;
            height: 48px;
            font-size: 14px;
            background: #fff;

            .get_verification {
              position: absolute;
              top: 50%;
              right: 10px;
              transform: translateY(-50%);
              border: 0;
              color: #ccc;
              font-size: 14px;
              background: transparent;
              &.right_phone {
                color: black
              }
            }
          }

          .login_verification {
            position: relative;
            margin-top: 16px;
            height: 48px;
            font-size: 14px;
            background: #fff;

            .switch_button {
              font-size: 12px;
              border: 1px solid #ddd;
              border-radius: 8px;
              transition: background-color 0.3s, border-color 0.3s;
              padding: 0 6px;
              width: 30px;
              height: 16px;
              line-height: 16px;
              color: #fff;
              position: absolute;
              top: 50%;
              right: 10px;
              transform: translateY(-50%);

              &.off {
                background: #fff;

                .switch_text {
                  float: right;
                  color: #ddd;
                }
              }

              &.on {
                background: #02a774;
              }

              >.switch_circle {
                // transform translateX(27px)
                position: absolute;
                top: -1px;
                left: -1px;
                width: 16px;
                height: 16px;
                border: 1px solid #ddd;
                border-radius: 50%;
                background: #fff;
                box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
                &.right {
                  transform translateX(30px)
                }  
              }
            }
          }

          .login_hint {
            margin-top: 12px;
            color: #999;
            font-size: 14px;
            line-height: 20px;

            >a {
              color: #02a774;
            }
          }
        }

        .login_submit {
          display: block;
          width: 100%;
          height: 42px;
          margin-top: 30px;
          border-radius: 4px;
          background: #4cd96f;
          color: #fff;
          text-align: center;
          font-size: 16px;
          line-height: 42px;
          border: 0;
        }
      }

      .about_us {
        display: block;
        font-size: 12px;
        margin-top: 20px;
        text-align: center;
        color: #999;
      }
    }

    .go_back {
      position: absolute;
      top: 5px;
      left: 5px;
      width: 30px;
      height: 30px;

      >.iconfont {
        font-size: 20px;
        color: #999;
      }
    }
  }
}
</style>